package com.itjin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {

  private static final Logger log = LoggerFactory.getLogger(RedisConfiguration.class);

  @Bean
  @Primary
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    log.info("开始创建redis模板对象...");
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    // 设置redis的连接工厂对象
    redisTemplate.setConnectionFactory(redisConnectionFactory);

    // 设置序列化器
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

    // 设置key和hashKey采用string的序列化方式
    redisTemplate.setKeySerializer(stringRedisSerializer);
    redisTemplate.setHashKeySerializer(stringRedisSerializer);

    // 设置value和hashValue采用jackson的序列化方式
    redisTemplate.setValueSerializer(jsonRedisSerializer);
    redisTemplate.setHashValueSerializer(jsonRedisSerializer);

    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }

  /**
   * 专门用于审核服务的RedisTemplate，使用String序列化器
   * 避免与Python服务的JSON格式冲突
   */
  @Bean("auditRedisTemplate")
  public RedisTemplate<String, String> auditRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    log.info("开始创建审核专用redis模板对象...");
    RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
    // 设置redis的连接工厂对象
    redisTemplate.setConnectionFactory(redisConnectionFactory);

    // 全部使用String序列化器
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(stringRedisSerializer);
    redisTemplate.setHashKeySerializer(stringRedisSerializer);
    redisTemplate.setValueSerializer(stringRedisSerializer);
    redisTemplate.setHashValueSerializer(stringRedisSerializer);

    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }
}
